Repository navigation
fix(streaming): read a streamed usage chunk that is an OpenAI SDK object - #41429
mrpavelgoodman wants to merge 6 commits into
Conversation
`_usage_chunk_calculation_helper` reads the aggregated usage block through the
Mapping protocol (`"prompt_tokens" in usage_chunk`, `usage_chunk.get(...)`) and
accepts token details only as a `dict` or as litellm's own wrapper. That holds
for a litellm `Usage`, which implements `__contains__`/`get`, but the chunk is
not always one: against an OpenAI-compatible upstream the aggregator receives
the OpenAI SDK's `CompletionUsage`, whose details are the SDK's own
`PromptTokensDetails` and `CompletionTokensDetails`.
`CompletionUsage` answers neither `in` nor `get`, so every token count read this
way came back zero and `calculate_usage` fell back to counting the prompt with
litellm's tokenizer; the isinstance chain matched neither detail model, so
`prompt_tokens_details` was dropped and `cached_tokens` never reached the
caller.
Measured against an OpenAI-compatible provider, one streamed request:
upstream sent prompt 37, completion 110 (reasoning 83), cached present
litellm reported prompt 14, completion 33, prompt_tokens_details None
after this change prompt 37, completion 125 (reasoning 103), details present
On a repeated 5234-token prefix the same request reports cached_tokens 4992
where it previously reported none, so a cache-heavy streaming workload was
being costed at the full input rate.
Attribute access replaces the Mapping reads -- a litellm `Usage` is a pydantic
model and answers those identically -- and a small coercion accepts any details
object that can be dumped. Covered both ways: an SDK `CompletionUsage` and a
litellm `Usage`.
Related: BerriAI#36168, BerriAI#37485. BerriAI#36906 restores `prompt_tokens_details` for the same
shape but leaves the token counts themselves at the tokenizer estimate.
Greptile SummaryThis PR changes streamed usage parsing to use attributes and adds token-detail coercion for OpenAI SDK models
Confidence Score: 4/5The behavior appears low risk, but repository requirements must be satisfied before merging The parsing change has no established runtime failure, but its untyped helper, excessive comments, and production-path test gap violate explicit repository guidance Files Needing Attention: litellm/litellm_core_utils/streaming_chunk_builder_utils.py, tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py Important Files Changed
Reviews (1): Last reviewed commit: "fix(streaming): read a streamed usage ch..." | Re-trigger Greptile |
| _TokenDetails = TypeVar("_TokenDetails", CompletionTokensDetails, PromptTokensDetailsWrapper) | ||
|
|
||
|
|
||
| def _as_token_details(value: Any, wrapper: type[_TokenDetails]) -> _TokenDetails | None: |
There was a problem hiding this comment.
Untyped helper parameter
_as_token_details accepts Any, violating the requirement that every function parameter be strongly typed. This must be fixed before merging
Context Used: CLAUDE.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| """Coerce a token-details object of any shape into litellm's own model. | ||
|
|
||
| A streamed usage block does not always arrive as a litellm ``Usage``. When the | ||
| upstream is OpenAI-compatible, the OpenAI SDK's ``CompletionUsage`` reaches the | ||
| aggregator with ``openai.types.completion_usage.PromptTokensDetails`` and | ||
| ``CompletionTokensDetails`` inside it, which are neither a ``dict`` nor | ||
| litellm's wrapper, so the previous isinstance chain dropped them and | ||
| ``cached_tokens`` was reported as absent on every streamed request. | ||
| """ |
There was a problem hiding this comment.
Excessive explanatory docstrings The new source and test docstrings restate straightforward behavior, violating the requirement to reserve comments for complex business logic. Fix before merging
Context Used: CLAUDE.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| completion_tokens_details=SDKCompletionTokensDetails(reasoning_tokens=103), | ||
| ) | ||
|
|
||
| summary: Final = ChunkProcessor.__new__(ChunkProcessor)._usage_chunk_calculation_helper(usage_chunk) |
There was a problem hiding this comment.
Regression test bypasses production The SDK test calls the private helper directly, skipping normalization and aggregation, so it does not protect the real production path. Fix before merging
Context Used: CLAUDE.md (source)
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
The strict-rule gate counts ANN401, and `Any` here bought nothing: the function only ever tests the value with `isinstance` and looks for `model_dump`, both of which `object` allows.
…prose Review asked for three things. The `Any` annotation is gone in the previous commit. The remaining two, here: the tests now drive the real aggregation path rather than calling the private helper, using the existing `_fail_prompt_token_count` so a silent fall back to the tokenizer fails the test rather than passing quietly; and the docstrings say what the code does once instead of restating it.
LIT002 counts mutable-collection literals, and these do not need to be mutable: the aggregator only reads them.
LIT002 counts it, and it was doing nothing: both wrappers accept the unset fields of a model_dump as None, which is what they already hold.
Both branches of the coercion are reachable through calculate_usage, so they are tested there rather than against the private helper.
|
Thanks for the contribution! #44349 now converts SDK usage objects to LiteLLM |
The problem
ChunkProcessor._usage_chunk_calculation_helperreads the aggregated streaming usage block through the Mapping protocol:and accepts token details only as a
dictor as litellm's ownPromptTokensDetailsWrapper/CompletionTokensDetails.That holds for a litellm
Usage, which implements__contains__andget. But the chunk is not always one: against an OpenAI-compatible upstream the aggregator receives the OpenAI SDK'sCompletionUsage, whose details areopenai.types.completion_usage.PromptTokensDetailsandCompletionTokensDetails.CompletionUsageanswers neitherinnorget, so:0, andcalculate_usagefell back to counting the prompt with litellm's own tokenizer;prompt_tokens_detailswas dropped andcached_tokensnever reached the caller.Measured
One streamed request against an OpenAI-compatible provider:
prompt_tokens_detailsAnd on a repeated 5234-token prefix the same streamed request now reports
cached_tokens: 4992where it previously reported nothing at all — so a cache-heavy streaming workload was being billed at the full input rate rather than the cache-read rate.The change
Attribute access replaces the Mapping reads. A litellm
Usageis a pydantic model and answersgetattridentically, so nothing changes for the shape that already worked. A small_as_token_detailscoercion accepts a wrapper, adict, or anything withmodel_dump().Two tests cover both shapes: an SDK
CompletionUsageand a litellmUsage.Related
usagewhen the final chunk has a non-emptychoicesarray (cached_tokens lost, cost billed at full input rate) #36168 and [Bug]: vercel_ai_gateway streaming drops prompt_tokens_details (cached_tokens) — regression since v1.95, overcharges cache-heavy streaming workloads #37485 describe this failure.prompt_tokens_detailsfor the same shape, but leaves the token counts themselves at the tokenizer estimate — thein/getreads above are the other half.